package com.team.childapp.listener

import android.content.Context
import android.media.AudioAttributes
import android.media.SoundPool
import androidx.recyclerview.widget.RecyclerView
import com.mig35.carousellayoutmanager.CarouselLayoutManager
import com.team.childapp.bean.MainItem

class CustomerCenterScrollListener (
    private val context: Context, // 用于访问资源
    private val list: List<MainItem> // 音频资源的 ID
    ) : RecyclerView.OnScrollListener() {

        private var soundPool: SoundPool? = null
        private var soundId: Int = -1
        private var isPlaying = false
        private var lastPosition=0;

        init {
            // 初始化 SoundPool
            val audioAttributes = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build()

            soundPool = SoundPool.Builder()
                .setMaxStreams(1) // 最大同时播放的音频流数量
                .setAudioAttributes(audioAttributes)
                .build()


        }

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)

            when (newState) {
                RecyclerView.SCROLL_STATE_IDLE -> {
                    // 滑动停止
                    val layoutManager = recyclerView.layoutManager as? CarouselLayoutManager
                    layoutManager?.let {
                        // 获取当前居中的 item 位置
                        val currentPosition = it.centerItemPosition
                        println("当前居中的 item 位置: $currentPosition")

                        // 如果当前居中的 item 是目标 item，播放音频
                        if (lastPosition!=currentPosition) {
                            playAudio(list.get(currentPosition).itemAudio)
                            lastPosition=currentPosition
                        }
                    }
                }
                RecyclerView.SCROLL_STATE_DRAGGING -> {
                    // 用户正在拖动
                    println("用户正在拖动")
                }
                RecyclerView.SCROLL_STATE_SETTLING -> {
                    // 自动滑动中
                    println("自动滑动中")
                }
            }
        }

        private fun playAudio(audioResourceId:Int) {
            // 加载音频资源
            soundId = soundPool?.load(context, audioResourceId, 1) ?: -1
            soundPool?.setOnLoadCompleteListener { soundPool, sampleId, status ->
                if (status == 0 && sampleId == soundId) { // 加载成功
                    soundPool.play(sampleId, 1.0f, 1.0f, 1, 0, 1.0f) // 播放音频
                }
            }
        }

        private fun stopAudio() {
            soundPool?.stop(soundId)
            isPlaying = false
        }

        fun release() {
            soundPool?.release()
            soundPool = null
        }
    }